package com.sgolub.commanndsonline.dao.sec;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.sgolub.commanndsonline.domain.sec.SecUser;


@Repository
public class SecUserDAOImpl implements SecUserDAO {

    @Autowired
    private SessionFactory sessionFactory;
	

	public SecUser get(Integer id) {
		SecUser secUser = (SecUser)sessionFactory.getCurrentSession().get(SecUser.class, id);
		return secUser;
	}

	public void add(SecUser secUser) {
		secUser.setRegDate(new Date());
		sessionFactory.getCurrentSession().save(secUser);
	}

	public void update(SecUser secUser) {
		sessionFactory.getCurrentSession().update(secUser);
	}

	public void remove(Integer id) {
		sessionFactory.getCurrentSession().delete(get(id));
		
	}

	@SuppressWarnings("unchecked")
	public SecUser	getByName(String name){
		String sql = "from SecUser where username = '" + name + "'";
		Query queryH = sessionFactory.getCurrentSession().createQuery(sql);
		List<SecUser> listUsers = queryH.list();
		
		if (listUsers.size() > 1) {
			System.out.println("AN EEROR OCCURED MORE THAN 2 Users with SAME username FOUND");
			return null;
		}
		
		SecUser secUser = (SecUser)listUsers.get(0);
		return secUser;
	}
	
	@SuppressWarnings("unchecked")
	public List<SecUser> list() {
		return sessionFactory.getCurrentSession().createQuery("from SecUser order by role_id, name asc ").list();
	}

	@SuppressWarnings("unchecked")
	public List<SecUser> listManagers(){
		return sessionFactory.getCurrentSession().createQuery("from SecUser where role_id = 2").list();
	}
	
}
